<template>
  <div class="app-container">
    <help :show-help="showHelp" />
    <div class="filter-container">
      <el-select
        v-model="listQuery.status"
        placeholder="状态"
        style="width: 120px"
        clearable
        class="filter-item"
        @change="handleFilter"
        @clear="clearStatus"
      >
        <el-option
          v-for="item in statusMap"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-if="false"
        v-model="listQuery.type"
        placeholder="类型"
        style="width: 120px; margin-left: 10px"
        clearable
        class="filter-item"
        @change="handleFilter"
        @clear="clearType"
      >
        <el-option
          v-for="item in [{value: 0, label: '普通订单'}, {value: 1, label: '拼团订单'}]"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-date-picker
        v-model="listQuery.start"
        class="filter-item"
        value-format="yyyy-MM-dd"
        type="date"
        style="margin-left: 10px"
        placeholder="开始日期"
        @change="handleFilter"
      />
      -
      <el-date-picker
        v-model="listQuery.end"
        class="filter-item"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="结束日期"
        @change="handleFilter"
      />
    </div>
    <div class="filter-container">
      <el-input
        v-model="listQuery.id"
        placeholder="订单ID"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.sn"
        placeholder="订单号"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.user_id"
        placeholder="会员ID"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.mobile"
        placeholder="手机号"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.product"
        placeholder="商品"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-button
        v-waves
        type="primary"
        icon="el-icon-search"
        class="filter-item"
        style="margin-left: 10px;"
        @click="handleFilter"
      >搜 索</el-button>
      <el-button
        v-waves
        type="success"
        icon="el-icon-refresh"
        class="filter-item"
        style="margin-left: 10px;"
        @click="clearFilter"
      >清除筛选</el-button>
    </div>
    <div class="filter-container">
      <el-button
        v-waves
        type="success"
        icon="el-icon-download"
        class="filter-item"
        size="small"
        plain
        :loading="listLoading"
        @click="handleExport"
      >导出 Excel</el-button>
      <el-button
        v-waves
        type="success"
        class="filter-item"
        size="small"
        plain
        @click="showHelp = !showHelp"
      >{{ showHelp ? '关闭帮助' : '显示帮助' }}</el-button>
      <el-button
        v-waves
        type="danger"
        icon="el-icon-upload"
        class="filter-item"
        size="small"
        plain
        :loading="listLoading"
        @click="handleImport"
      >导入快递列表</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :border="false"
      fit
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column v-if="listShow.id" sortable="custom" prop="id" label="ID" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="sn" label="SN" width="200">
        <template slot-scope="{row: { snWrapper }}">
          <span v-html="snWrapper" />
        </template>
      </el-table-column>
      <el-table-column label="用户" sortable="custom" prop="user_id" width="100">
        <template slot-scope="{row}">
          <span>{{ row.user_id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品" align="left" width="300">
        <template slot-scope="{row}">
          <span>
            <p v-for="(o, i) in row.item" :key="i">
              <template v-if="o.product">
                {{ o.product.title }} x {{ o.quantity }}
              </template>
            </p>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" width="150">
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总数量" align="center">
        <template slot-scope="{row}">
          <span>{{ row.total_quantity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" sortable="custom" prop="total_pay" width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ +row.total_pay }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="false" label="类型">
        <template slot-scope="{row}">
          <span>{{ row.is_group | typeText }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" sortable="custom" prop="status" align="center">
        <template slot-scope="{row}">
          <span>{{ row.status | statusText }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="listShow.date" label="下单时间" sortable="custom" prop="create_time" width="160">
        <template slot-scope="{row:{create_time}}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ create_time | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="线下打款" align="center">
        <template slot-scope="{row}">
          <span v-if="+row.pay_type === -88">
            <!--            <el-link type="warning">查看凭证</el-link>-->
            <div v-if="row.offline && row.offline.length > 0" class="demo-image__lazy">
              <el-image :src="row.offline[0]" lazy :fit="'cover'" :preview-src-list="row.offline">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
            </div>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="评论列表">
        <template slot-scope="{row}">
          <span><el-link type="danger" @click="$router.push(`/order/comment/${row.id}`)">查看</el-link></span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="220"
        fixed="right"
      >
        <template slot-scope="{ row }">
          <el-button type="success" size="mini" icon="el-icon-edit" @click="handleView(row)">
            详情
          </el-button>
          <el-button type="danger" size="mini" @click="resetCommission(row)">
            重新计算佣金
          </el-button>
          <el-button v-if="+row.pay_type === -88 && +row.status === 0" type="warning" size="mini" @click="handleOffline(row)">
            确认打款
          </el-button>
          <template v-if="+row.status !== 6 && false">
            <el-divider />
            <el-button type="warning" size="mini" @click="handleBack(row)">
              退款
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      @pagination="refresh"
    />
    <el-dialog
      title="请上传"
      :visible.sync="dialogVisible"
      width="400px"
    >
      <span>
        <el-upload
          class="upload-demo"
          drag
          :action="action"
          :multiple="false"
          :headers="headers"
          :on-success="onSuccess"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">只能上传excel文件, 必须先用导出的订单列表填写</div>
        </el-upload>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import api from '@/api'
import Help from './components/Help'
import config from '@/config'

const initQuery = {
  status: config.order.OPEN,
  page: 1,
  pageSize: 10,
  total: 0,
  sort: '+id'
}

export default {
  name: 'OrderList',
  components: {
    Pagination,
    Help
  },
  directives: { waves },
  filters: {
    timeFilter(time) {
      return time ? parseTime(time, '{m}-{d} {h}:{i}') : ''
    },
    statusText(status) {
      return config.order.statusText(+status)
    },
    typeText(v) {
      return +v === 1 ? '拼团' : '普通'
    }
  },
  data() {
    return {
      // 状态
      status: {},
      // 状态
      statusMap: [],
      // 显示帮助提示
      showHelp: false,
      listLoading: false,
      list: [],
      listQuery: {
        type: 0
      },
      defaultSort: {},
      // selectionList: [],
      // 显示控制
      listShow: {
        id: true,
        date: true
      },
      dialogVisible: false,
      use_balance_total: 0,
      use_money_total: 0
    }
  },
  computed: {
    headers() {
      return {
        // 'X-Admin-YANG': getToken()
        [process.env.VUE_APP_TOKEN]: getToken()
      }
    },
    action() {
      return `${process.env.VUE_APP_BASE_API}/api/upload/express`
    }
  },
  created() {
    this.parseQuery()
    this.getOrderTotal()
  },
  mounted() {
    this.getStatusList()
    this.getList()
  },
  methods: {
    // 总计
    getOrderTotal() {
      api.finance.getOrderTotal().then(response => {
        const { data } = response
        this.use_balance_total = data.use_balance
        this.use_money_total = data.use_money
      })
    },
    handleBack(row) {
      this.$confirm('您确定要退款吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.order.refund({ id: row.id }).then(response => {
          this.$message({
            message: response.message || '退款成功',
            type: 'success'
          })
          this.list.forEach(x => {
            if (x.id === row.id) {
              x.status = this.status.REFUND
            }
          })
          // 删除掉
          this.list = this.list.filter(x => +x.status !== this.status.REFUND)
          // this.handleFilter()
        })
      }).catch(() => {})
    },
    handleOffline(row) {
      this.$confirm('您确定要审核打款吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.order.offline({ id: row.id }).then(response => {
          this.$message({
            message: response.message || '审核成功',
            type: 'success'
          })
          this.list.forEach(x => {
            if (x.id === row.id) {
              x.status = this.status.PAID
            }
          })
        })
      }).catch(() => {})
    },
    resetCommission(item) {
      this.listLoading = true
      api.order.resetCommission({ id: item.id }).then(() => {
        this.$message.success('操作成功')
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleView(item) {
      // 查看详情
      this.$router.push(`/order/order-view/${item.id}`)
    },
    /**
     * 清除状态
     */
    clearStatus() {
      // this.listQuery.status = config.order.ALL
      this.listQuery.status = null
    },
    /**
     * 清除类型
     */
    clearType() {
      // this.listQuery.status = config.order.ALL
      this.listQuery.type = null
    },
    /**
     * 获取状态列表
     */
    getStatusList() {
      this.listLoading = true
      api.order.statusList().then(response => {
        const { data } = response
        this.statusMap = data
        this.listLoading = false
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 查询高亮
     */
    wrapperKeyword(k, v) {
      const highlight = value => {
        return `<span style="color: #1890ff">${value}</span>`
      }
      if (!this.listQuery[k]) {
        return v
      }
      return v.replace(new RegExp(this.listQuery[k], 'ig'), v => highlight(v))
    },
    /**
     * 获取数据列表
     */
    getList() {
      this.listLoading = true
      // 状态需要处理
      if (this.listQuery.status === '') {
        this.listQuery.status = initQuery.status
      }
      api.order.list({ ...this.listQuery }).then(response => {
        const { data } = response
        this.list = data.list
        this.listQuery.total = +data.totalCount
        this.listLoading = false
        this.list.forEach(x => {
          // 搜索高亮
          x.snWrapper = this.wrapperKeyword('sn', x.sn)
        })
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 排序
     * @param data
     */
    sortChange(data) {
      const sortBy = (prop, order) => {
        if (prop && order === 'ascending') {
          this.listQuery.sort = `+${prop}`
        } else if (prop && order === 'descending') {
          this.listQuery.sort = `-${prop}`
        } else {
          this.listQuery.sort = ''
        }
      }
      const { prop, order } = data
      sortBy(prop, order)
      this.handleFilter()
    },
    /**
     * 刷新
     */
    refresh() {
      this.$router.push({
        path: '/order/list',
        query: this.listQuery
      })
    },
    /**
     * 过滤(筛选)
     */
    handleFilter() {
      // this.listQuery.page = 1
      this.refresh()
    },
    /**
     * 清除筛选
     */
    clearFilter() {
      this.listQuery = Object.assign({}, initQuery)
      this.defaultSort = {}
      this.refresh()
    },
    /**
     * 处理筛选条件
     */
    parseQuery() {
      const query = Object.assign({}, this.$route.query)
      let sort = '-id'
      this.listQuery = Object.assign({}, { ...initQuery, sort })
      if (Object.keys(query).length > 0) {
        // 注意这里的类型转换
        query.page && (query.page = +query.page)
        query.pageSize && (query.pageSize = +query.pageSize)
        query.total && (query.total = +query.total)
        query.status && (query.status = +query.status)
        query.sort && (sort = query.sort)
      }
      const sortSymbol = sort[0]
      const sortColumn = sort.slice(1, sort.length)
      this.defaultSort = {
        prop: sortColumn,
        order: sortSymbol === '+' ? 'ascending' : 'descending'
      }
      this.listQuery = { ...this.listQuery, ...query }
      this.status = config.order
    },
    /**
     * 导出
     */
    async handleExportOld() {
      const formatJson = (filterVal, jsonData) => {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'status') {
            return config.order.statusText(+v['status'])
          }
          if (j === 'type') {
            return this.$options.filters.typeText(v['is_group'])
          }
          if (j === 'product') {
            return v['item'].map(i => {
              if (!i.product) {
                return ''
              }
              if (i.selected_sku_text && i.selected_sku_text !== 'null') {
                return `${i.product.title} (${JSON.parse(i.selected_sku_text).join(', ')}) x ${i.quantity}`
              }
              return `${i.product.title} x ${i.quantity}`
            })
          }
          // user
          if (j === 'user') {
            if (v['user']) {
              return `id: ${v['user'].id} (电话: ${v['user'].mobile})`
            }
            return ''
          }
          // express
          if (j === 'express') {
            if (v['address']) {
              return `收件人: ${v['address'].nickname} (收件电话: ${v['address'].mobile})`
            }
            return ''
          }
          if (j === 'express_address') {
            if (v['address'] && v['address'].city) {
              return `${v['address'].city.province} ${v['address'].city.city} ${v['address'].city.area} ${v['address'].address}`
            }
            return ''
          }
          return v[j]
        }))
      }
      this.listLoading = true
      if (this.listQuery.status === '') {
        this.listQuery.status = initQuery.status
      }
      const response = await api.order.list({ ...this.listQuery, export: true })
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', 'sn', '状态', '类型', '下单时间', '会员',
          '商品', /* '商品总金额', '总运费',*/ '支付总金额', '使用余额', '使用积分', '使用平台券', '使用现金',
          '收件人', '收货地址']
        const filterVal = ['id', 'sn', 'status', 'type', 'create_time', 'user',
          'product', /* 'total_price', 'total_freight',*/ 'total_pay', 'use_balance', 'use_score', 'use_platform_ticket', 'use_money',
          'express', 'express_address']
        const list = response.data
        const data = formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '订单列表'
        })
      })
      this.listLoading = false
    },
    async handleExport() {
      const formatJson = (filterVal, jsonData) => {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'status') {
            return config.order.statusText(+v['status'])
          }
          if (j === 'type') {
            // return this.$options.filters.typeText(v['is_group'])
            return this.$options.filters.typeText(v['store'])
          }
          if (j === 'product') {
            return v['item'].map(i => {
              if (!i.product) {
                return ''
              }
              if (i.selected_sku_text && i.selected_sku_text !== 'null') {
                return `${i.product.title} (${JSON.parse(i.selected_sku_text).join(', ')}) x ${i.quantity}`
              }
              return `${i.product.title} x ${i.quantity}`
            })
          }
          // user
          if (j === 'user') {
            if (v['user']) {
              return `id: ${v['user'].id} (电话: ${v['user'].mobile})`
            }
            return ''
          }
          // express
          if (j === 'express') {
            if (v['address']) {
              return `收件人: ${v['address'].nickname} (收件电话: ${v['address'].mobile})`
            }
            return ''
          }
          if (j === 'express_address') {
            if (v['address'] && v['address'].city) {
              return `${v['address'].city.province} ${v['address'].city.city} ${v['address'].city.area} ${v['address'].address}`
            }
            return ''
          }
          if (j === 'express_save' || j === 'express_company') {
            return ''
          }
          return v[j]
        }))
      }
      this.listLoading = true
      if (this.listQuery.status === '') {
        this.listQuery.status = initQuery.status
      }
      const response = await api.order.list({ ...this.listQuery, export: true })
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', 'sn', '状态', '类型', '下单时间', '会员',
          '商品', /* '商品总金额', '总运费',*/ '支付总金额', '使用平台券', '使用现金',
          '收件人', '收货地址', '快递单号(请填写)', '快递公司编码(后台查看)']
        const filterVal = ['id', 'sn', 'status', 'type', 'create_time', 'user',
          'product', /* 'total_price', 'total_freight',*/ 'total_pay', 'use_platform_ticket', 'use_money',
          'express', 'express_address', 'express_save', 'express_company']
        const list = response.data
        const data = formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '订单列表'
        })
      })
      this.listLoading = false
    },
    handleImport() {
      this.dialogVisible = true
    },
    onSuccess(data) {
      if (data.code === 0) {
        this.$message({
          message: `操作成功, 共完成${data.data.length}条`,
          type: 'success'
        })
        this.dialogVisible = false
      } else if (data.code === -1) {
        this.$message({
          message: data.message,
          type: 'error'
        })
      }
    }
  },
  /**
   * 刷新
   * @param to
   * @param from
   * @param next
   */
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      const newQuery = Object.assign({}, to.query)
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getList()
      }
    }
    next()
  }
}
</script>

<style scoped lang="scss">
.el-divider--horizontal {
  margin: 5px 0;
}
</style>

